JIRA.IssuePicker = AJS.MultiSelect.extend({
    _formatResponse: function (response) {
        var ret = [],
            canonicalBaseUrl = (function () {
                var uri = parseUri(window.location);
                return uri.protocol + "://" + uri.authority
            })();
        if (response && response.sections) {
            AJS.$(response.sections).each(function (i, section) {
                var groupDescriptor = new AJS.GroupDescriptor({
                    weight: i,
                    label: section.label,
                    description: section.sub
                });
                if (section.issues && section.issues.length > 0) {
                    AJS.$(section.issues).each(function () {
                        groupDescriptor.addItem(new AJS.ItemDescriptor({
                            value: this.key,
                            label: this.key + " - " + this.summaryText,
                            icon: this.img ? canonicalBaseUrl + contextPath + this.img : null,
                            html: this.keyHtml + " - " + this.summary
                        }))
                    })
                }
                ret.push(groupDescriptor)
            })
        }
        return ret
    },
    getAjaxOptions: function () {
        var ajaxOptions = this._super();
        if (this.$field.val().length === 0) {
            delete ajaxOptions.data.currentJQL
        }
        return ajaxOptions
    },
    hasUserInputtedOption: function () {
        return this.$field.val().length !== 0
    },
    _launchPopup: function () {
        function getWithDefault(value, def) {
            if (typeof value == "undefined" || value == null) {
                return def
            } else {
                return value
            }
        }
        var url, urlParam, vWinUsers, options, instance = this;
        JIRA.IssuePicker.callback = function (items) {
            if (typeof items === "string") {
                items = JSON.parse(items)
            }
            instance._addMultipleItems(items, true);
            instance.$field.focus()
        };
        options = this.options.ajaxOptions.data;
        url = contextPath + "/secure/popups/IssuePicker.jspa?";
        urlParam = {
            singleSelectOnly: "false",
            currentIssue: options.currentIssueKey || "",
            showSubTasks: getWithDefault(options.showSubTasks, false),
            showSubTasksParent: getWithDefault(options.showSubTaskParent, false)
        };
        if (options.currentProjectId) {
            urlParam["currentProjectId"] = options.currentProjectId
        }
        url += AJS.$.param(urlParam);
        vWinUsers = window.open(url, "IssueSelectorPopup", "status=no,resizable=yes,top=100,left=200,width=" + this.options.popupWidth + ",height=" + this.options.popupHeight + ",scrollbars=yes,resizable");
        vWinUsers.opener = self;
        vWinUsers.focus()
    },
    _createFurniture: function (disabled) {
        var $popupLink;
        this._super(disabled);
        $popupLink = this._render("popupLink");
        this._assignEvents("popupLink", $popupLink);
        this.$container.addClass("hasIcon");
        $popupLink.appendTo(this.$container)
    },
    handleFreeInput: function () {
        var values = this.$field.val().toUpperCase().match(/\S+/g);
        if (values) {
            this._addMultipleItems(jQuery.map(values, function (value) {
                return {
                    value: value,
                    label: value
                }
            }))
        }
        this.$field.val("")
    },
    _events: {
        popupLink: {
            click: function (e) {
                this._launchPopup();
                e.preventDefault()
            }
        }
    },
    _renders: {
        popupLink: function () {
            return AJS.$("<a class='issue-picker-popup' />").attr({
                href: "#",
                title: this.options.popupLinkMessage
            }).text("" + this.options.popupLinkMessage + "")
        }
    }
});
AJS.namespace("jira.issuepicker", null, JIRA.IssuePicker);
AJS.namespace("AJS.IssuePicker", null, JIRA.IssuePicker);
JIRA.LabelPicker = AJS.MultiSelect.extend({
    _getDefaultOptions: function () {
        return AJS.$.extend(true, this._super(), {
            ajaxOptions: {
                url: contextPath + "/includes/js/ajs/layer/labeldata.js",
                query: true
            },
            removeOnUnSelect: true,
            userEnteredOptionsMsg: AJS.params.labelNew
        })
    },
    isValidItem: function (itemValue) {
        return !/\s/.test(itemValue)
    },
    _handleSuggestionResponse: function (data) {
        if (data && data.token) {
            if (AJS.$.trim(this.$field.val()) !== data.token) {
                return
            }
        }
        this._super(data)
    },
    _handleDown: function (e) {
        if (!this.suggestionsVisible) {
            this._requestThenResetSuggestions();
            e.stopPropagation()
        }
    },
    _handleSpace: function () {
        if (AJS.$.trim(this.$field.val()) !== "") {
            if (this.handleFreeInput()) {
                this.hideSuggestions()
            }
        }
    },
    keys: {
        space: function (e) {
            this._handleSpace();
            e.preventDefault()
        }
    },
    _formatResponse: function (data) {
        var optgroup = new AJS.GroupDescriptor({
            label: AJS.params.frotherSuggestions,
            type: "optgroup",
            weight: 1,
            styleClass: "labels-suggested"
        });
        if (data && data.suggestions) {
            AJS.$.each(data.suggestions, function () {
                optgroup.addItem(new AJS.ItemDescriptor({
                    value: this.label,
                    label: this.label,
                    html: this.html
                }))
            })
        }
        return [optgroup]
    },
    handleFreeInput: function () {
        var values = AJS.$.trim(this.$field.val()).match(/\S+/g);
        if (values) {
            for (var value, i = 0; value = values[i]; i++) {
                this._addItem({
                    value: value,
                    label: value
                })
            }
            this.model.$element.trigger("change")
        }
        this.$field.val("")
    }
});
AJS.namespace("AJS.LabelPicker", null, JIRA.LabelPicker);
AJS.$(function () {
    function initCascadingSelect(el) {
        AJS.$(el || document.body).find("div.aui-field-cascadingselect").add("tr.aui-field-cascadingselect").add("td.aui-field-cascadingselect").each(function () {
            var $container = AJS.$(this),
                parent = $container.find(".cascadingselect-parent"),
                parentOptions = parent.find("option"),
                oldClass = "",
                child = $container.find(".cascadingselect-child"),
                childOptions = child.find("option"),
                selectedChild = child.find(":selected");

            function update() {
                var currentClass = parent.find("option:selected").attr("class");
                if (currentClass !== oldClass) {
                    child.find("option").remove();
                    childOptions.filter("." + parent.find("option:selected").attr("class")).appendTo(child);
                    if (selectedChild.hasClass(parent.find("option:selected").attr("class"))) {
                        child.val(selectedChild.val())
                    } else {
                        child.val(child.find("option:first").val())
                    }
                    oldClass = currentClass
                }
            }
            parent.bind("cascadingSelectChanged", update).change(function () {
                AJS.$(this).trigger("cascadingSelectChanged")
            }).trigger("cascadingSelectChanged")
        })
    }
    initCascadingSelect();
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        initCascadingSelect(dialog.get$popupContent())
    })
});
(function () {
    function createPicker($selectField) {
        new AJS.MultiSelect({
            element: $selectField,
            itemAttrDisplayed: "label",
            errorMessage: AJS.params.multiselectComponentsError
        })
    }
    function locateSelect(parent) {
        var $parent = AJS.$(parent),
            $selectField;
        if ($parent.is("select")) {
            $selectField = $parent
        } else {
            $selectField = $parent.find("select")
        }
        return $selectField
    }
    var DEFAULT_SELECTORS = ["div.aui-field-componentspicker.frother-control-renderer", "td.aui-field-componentspicker.frother-control-renderer", "tr.aui-field-componentspicker.frother-control-renderer"];

    function findComponentSelectAndConvertToPicker(context, selector) {
        selector = selector || DEFAULT_SELECTORS.join(", ");
        AJS.$(selector, context).each(function () {
            var $selectField = locateSelect(this);
            if ($selectField.length) {
                createPicker($selectField)
            }
        })
    }
    AJS.$(function () {
        findComponentSelectAndConvertToPicker()
    });
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        findComponentSelectAndConvertToPicker(dialog.get$popupContent())
    })
})();
AJS.$(function () {
    function initDatePicker(el) {
        AJS.$(el || document.body).find("div.aui-field-datepicker").add("tr.aui-field-datepicker").add("td.aui-field-datepicker").each(function () {
            var $container = AJS.$(this),
                field = $container.find("input:text"),
                defaultCheckbox = $container.find("#useCurrentDate"),
                params = JIRA.parseOptionsFromFieldset($container.find("fieldset.datepicker-params"));
            params.context = el;
            Calendar.setup(params);

            function toggleField() {
                field.attr("disabled", defaultCheckbox.is(":checked"))
            }
            if (defaultCheckbox.length) {
                toggleField();
                defaultCheckbox.click(toggleField)
            }
        })
    }
    initDatePicker();
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        initDatePicker(dialog.get$popupContent())
    })
});
AJS.$(function () {
    function initGroupPicker(el) {
        AJS.$(el || document.body).find("div.aui-field-grouppicker").add("tr.aui-field-grouppicker").add("td.aui-field-grouppicker").each(function () {
            var $container = AJS.$(this),
                trigger = $container.find("a.grouppicker-trigger"),
                url = trigger.attr("href");

            function openGroupPickerWindow(e) {
                e.preventDefault();
                window.open(url, "GroupPicker", "status=yes,resizable=yes,top=100,left=200,width=580,height=750,scrollbars=yes")
            }
            trigger.click(openGroupPickerWindow)
        })
    }
    initGroupPicker();
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        initGroupPicker(dialog.get$popupContent())
    })
});
(function () {
    function createPicker($fieldset) {
        var opts = JIRA.parseOptionsFromFieldset($fieldset),
            $select = AJS.$("#" + opts.id),
            issueId = opts.issueId,
            data = {};
        if (/customfield_\d/.test(opts.id)) {
            data.customFieldId = parseInt(opts.id.replace("customfield_", ""), 10)
        }
        new JIRA.LabelPicker({
            element: $select,
            ajaxOptions: {
                url: contextPath + "/rest/api/1.0/labels" + (issueId ? "/" + issueId : "") + "/suggest",
                data: data
            }
        })
    }
    function locateFieldset(parent) {
        var $parent = AJS.$(parent),
            $fieldset;
        if ($parent.is(FIELDSET_SELECTOR)) {
            $fieldset = $parent
        } else {
            $fieldset = $parent.find(FIELDSET_SELECTOR)
        }
        return $fieldset
    }
    var DEFAULT_SELECTORS = ["div.aui-field-labelpicker", "td.aui-field-labelpicker", "tr.aui-field-labelpicker"];
    var FIELDSET_SELECTOR = "fieldset.labelpicker-params";

    function findLabelsFieldsetAndConvertToPicker(context, selector) {
        selector = selector || DEFAULT_SELECTORS.join(", ");
        AJS.$(selector, context).each(function () {
            var $fieldset = locateFieldset(this);
            if ($fieldset.length > 0) {
                createPicker($fieldset)
            }
        })
    }
    AJS.$(function () {
        findLabelsFieldsetAndConvertToPicker()
    });
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        findLabelsFieldsetAndConvertToPicker(dialog.get$popupContent())
    })
})();
(function () {
    function createPicker($selectField) {
        new AJS.MultiSelect({
            element: $selectField,
            itemAttrDisplayed: "label",
            errorMessage: AJS.params.multiselectVersionsError
        })
    }
    function locateSelect(parent) {
        var $parent = AJS.$(parent),
            $selectField;
        if ($parent.is("select")) {
            $selectField = $parent
        } else {
            $selectField = $parent.find("select")
        }
        return $selectField
    }
    var DEFAULT_SELECTORS = ["div.aui-field-versionspicker.frother-control-renderer", "td.aui-field-versionspicker.frother-control-renderer", "tr.aui-field-versionspicker.frother-control-renderer"];

    function findVersionSelectAndConvertToPicker(context, selector) {
        selector = selector || DEFAULT_SELECTORS.join(", ");
        AJS.$(selector, context).each(function () {
            var $selectField = locateSelect(this);
            if ($selectField.length) {
                createPicker($selectField)
            }
        })
    }
    AJS.$(function () {
        findVersionSelectAndConvertToPicker()
    });
    AJS.$(document).bind("dialogContentReady", function (e, dialog) {
        findVersionSelectAndConvertToPicker(dialog.get$popupContent())
    })
})();